const { SuccessModel, ErrorModel } = require('../model/resModel')
const {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
} = require('../controller/blog')

const handleBlogRouter = (req, res) => {
    const method = req.method
    const id = req.query.id || ''
    // 获取博客列表
    if (method === 'GET' && req.path === '/api/blog/list') {
        const author = req.query.author || ''
        const keyword = req.query.keyword || ''
        // const data = getList(author, keyword)
        // return new SuccessModel(data)
        return getList(author, keyword).then(res => {
            return new SuccessModel(res)
        })
    }

    // 获取博客详情
    if (method === 'GET' && req.path === '/api/blog/detail') {
        // const data = getDetail(id)
        // return new SuccessModel(data)
        return getDetail(id).then(data => {
            return new SuccessModel(data)
        })
    }
    // 新建一篇博客
    if (method === 'POST' && req.path === '/api/blog/new') {
        req.body.ahthor = 'zhangsan' // 未登陆前，是没有author的，先写一个假数据
        const blogData = req.body
        return newBlog(blogData).then(data => {
            return new SuccessModel(data)
        })
    }
    // 更新一篇博客
    if (method === 'POST' && req.path === '/api/blog/update') {
        return updateBlog(id, req.body).then(val => {
            // val值是true 或者 false
            if (val) {
                return new SuccessModel()
            } else {
                return new ErrorModel('更新博客失败')
            }
        })
    }
    // 删除一篇博客
    if (method === 'POST' && req.path === '/api/blog/del') {
        const author = 'zhangsan' // 假数据，待开发登陆时改成真数据
        return delBlog(id, author).then(val => { // val为true 或者 false
            if (val) {
                return new SuccessModel()
            } else {
                return new ErrorModel('删除博客失败')
            }
        })
    }
}

module.exports = handleBlogRouter
